//
//  BodyBase.m
//  QBIM
//
//  Created by liunian on 14-3-17.
//  Copyright (c) 2014年 liunian. All rights reserved.
//

#import "BodyBase.h"
#import "JSON.h"

@implementation BodyBase
- (void)dealloc
{
    [super dealloc];
}

- (void)setI:(int)I
{
    QB_SET_RETAIN_NUMPARM(I, @"I");
}
@end

@implementation AuthBody
- (void)dealloc
{
    RELEASE_SAFELY(_V);
    RELEASE_SAFELY(_AP);
    [super dealloc];
}

- (void)setV:(NSString *)V{
    QB_SET_RETAINPARM(V, @"V");
}

- (void)setAT:(AuthType)AT{
    QB_SET_RETAIN_NUMPARM(AT, @"AT");
}

- (void)setAP:(NSString *)AP{
    QB_SET_RETAINPARM(AP, @"AP");
}

@end

@implementation BeatBody
- (void)dealloc
{
    RELEASE_SAFELY(_CT);
    [super dealloc];
}

- (void)setCT:(NSString *)CT{
    QB_SET_RETAINPARM(CT, @"CT");
}
@end

@implementation StatusBody
- (void)dealloc
{
    RELEASE_SAFELY(_U);
    [super dealloc];
}

- (void)setU:(NSString *)U{
    QB_SET_RETAINPARM(U, @"U");
}

- (void)setST:(NSString *)ST{
    QB_SET_RETAINPARM(ST, @"ST");
}

@end

@implementation RespBody
- (void)dealloc
{
    RELEASE_SAFELY(_EM);
    [super dealloc];
}

- (void)setEC:(int)EC
{
    QB_SET_RETAIN_NUMPARM(EC, @"EC");
}

- (void)setEM:(NSString *)EM{
    QB_SET_RETAINPARM(EM, @"EM");
}

@end

@implementation SysCMDBody
- (void)dealloc
{
    RELEASE_SAFELY(_P);
    [super dealloc];
}

- (void)setP:(SysCMDPayload *)P
{
    QB_SET_RETAINPARM(P, @"P");
}

@end

uint64_t htonll(uint64_t n) {
    return (((uint64_t)htonl(n)) << 32) | htonl(n >> 32);
}

uint64_t ntohll(uint64_t n) {
    return (((uint64_t)ntohl(n)) << 32) | ntohl(n >> 32);
}
@implementation MessageBody
- (void)dealloc
{
    RELEASE_SAFELY(_M);
    [super dealloc];
}

- (void)setM:(NSArray *)M
{
    QB_SET_RETAINPARM(M, @"M");
}

@end

@implementation HeaderBody

- (id)initWithBody:(id)body{
    if (self = [super init]) {
        self.packetFormat = PacketFormatPlain;
        if ([body isKindOfClass:[NSString class]]) {
            self.bodyJSON = body;
        }else{
            NSDictionary *d = [body parm2jsonObj];
            self.bodyJSON = [d JSONRepresentation];
        }
    }
    return self;
}

- (NSData *)prepareSendData{

    NSData *requestData = [self.bodyJSON dataUsingEncoding:NSUTF8StringEncoding];
    
    Byte ptByte[] = {self.packetType};
    Byte pfByte[] = {self.packetFormat};
    
    int32_t length = [requestData length];
    length = htonl(length);
    NSMutableData *lengthData = [NSMutableData dataWithBytes:&length length:sizeof(int32_t)];
    [lengthData appendBytes:ptByte length:1];   //追加字符串
    [lengthData appendBytes:pfByte length:1];
    [lengthData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSMutableData *mixData = [[NSMutableData alloc] initWithData:lengthData];
    [mixData appendData:requestData];
    DBLog(@"json:%@",self.bodyJSON);
    return mixData;
}

@end